package org.yhtch.jswtdic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.yhtch.jswtdic.res.R;

public class DicCore {
	private HashMap<String, String> wordbuf = new HashMap<String, String>();
	// private HashMap<String, String> newWordBuf=new HashMap<String, String>();
	// private JDicCore(){}
	private boolean findFromNet = false;
	private final String partSeprater = "}(}(";

	public DicCore() {
		try {
			Scanner in = new Scanner(new GZIPInputStream(new FileInputStream(R
					.getR().getDicFilePath())), "UTF-8");
			// System.out.println(dicFile.length());
			// System.out.println(in.hasNextLine());
			while (in.hasNextLine()) {
				String line = in.nextLine();
				StringTokenizer stk = new StringTokenizer(line, "\t");
				String word = stk.nextToken();
				String explain = stk.nextToken();
				wordbuf.put(word, explain);
				// System.out.println(word+":"+explain);
			}
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addWord(String word, String explain) {
		explain=explain.replace("\r\n", partSeprater);
		explain=explain.replace("\n", partSeprater);
		wordbuf.put(word, explain);
	}

	public String explainWord(String word) {
		String explain = wordbuf.get(word);
		if (null == explain && findFromNet) {
			explain = getExplainFromNet(word);
			if (null != explain)
				addWord(word, explain);
		}
		if (null != explain)
			explain = explain.replace(partSeprater, "\n");
		return explain;
	}

	public void close() {
		try {

			/*
			 * FileOutputStream dicFile=new
			 * FileOutputStream("dicts/dic.dat",true); PrintStream out=new
			 * PrintStream(dicFile, true, "UTF-8");
			 */
			PrintStream out = new PrintStream(new GZIPOutputStream(
					new FileOutputStream(R.getR().getDicFilePath())), true,
					"UTF-8");

			Iterator<String> iterator = wordbuf.keySet().iterator();
			while (iterator.hasNext()) {
				String word = iterator.next();
				String explain = wordbuf.get(word);
				out.println(word + "\t" + explain);
				// out.println(word+"\t"+explain);
			}
			// out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * public void listWords() { Set<String> word=wordbuf.keySet(); int
	 * index=0; while(index<word.size()) {
	 * System.out.println(word.toArray()[index]); } }
	 */
	public boolean isFindFromNet() {
		return findFromNet;
	}

	public void setFindFromNet(boolean findFromNet) {
		this.findFromNet = findFromNet;
	}

	/*
	 * private String getExplainFromNet(String word) { final String prefix =
	 * "http://www.dict.cn/search/?q="; final String stamp0 = "<span
	 * class=pronounce>"; final String stamp1 = "<big><font size=\"2\"
	 * face=\"Trebuchet MS\">"; URL url = null; Scanner in = null; try { url =
	 * new URL(prefix + word); in = new Scanner(url.openStream(), "GB2312"); }
	 * catch (IOException e) { e.printStackTrace(); return null; } String line =
	 * null; String explain = ""; boolean find = false; while (in.hasNextLine()) {
	 * line = in.nextLine(); if (line.contains("对不起,这个单词没找到!")) return null; if
	 * (line.indexOf(stamp0) != -1) { explain +=
	 * HtmlEntityComplexChar.decode(line.substring(line .indexOf(stamp0) +
	 * stamp0.length(), line.indexOf("</span>")));
	 * 
	 * if(explain.startsWith("对不起,这个单词没找到!")) return null; // explain+=line find =
	 * true; continue; } if (line.indexOf(stamp1) != -1) { explain +=
	 * partSeprater + line.substring( line.indexOf(stamp1) + stamp1.length(),
	 * line .indexOf("<br>")); find = true; continue; } if (find) { if
	 * (line.startsWith("</big>")) { find = false; break; } else if
	 * (line.indexOf("<br>") != -1) explain += partSeprater +
	 * line.substring(0, line.indexOf("<br>")); } } return explain; }
	 */

	/**
	 * 使用Dict.CN官方提供的xml接口从网络获取词条解释
	 * 
	 * @param word
	 *            被解释词条
	 * @return 指定词条的释义
	 */
	private String getExplainFromNet(String word) {
		final String prefix = "http://dict.cn/ws.php?q=";
		String explain = "";
		try {
			URL url = new URL(prefix + word);
			SAXBuilder builder = new SAXBuilder(false);
			Document dictxml = builder.build(url);
			Element dict = dictxml.getRootElement();
			String pron = dict.getChildText("pron");
			String def = dict.getChildText("def");
			if (null == def)
				return null;
			if (null != pron)
				explain += "[" + pron + "]";
			if (!"Not Found".equals(def))
				explain += partSeprater + def.replace(";\n", partSeprater);
			else
				return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return explain;
	}

	public static void main(String[] args) {
		DicCore dic = new DicCore();
		System.out.println(dic.getExplainFromNet("love"));
	}
}
